package dao

import javax.inject.Inject
import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future


/**
 * Created by yz on 2018/5/29
 */
class MetaboDbDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {

  import profile.api._

  def selectAll(userId: Int) = db.run(MetaboDb.filter(_.userId === userId).result)

  def select(id: Int) = db.run(MetaboDb.filter(_.id === id).result.head)

  def selectOp(id: Int) = db.run(MetaboDb.filter(_.id === id).result.headOption)

  def insert(row: MetaboDbRow) = db.run(MetaboDb += row).map(_ => ())

  def insertAndReturnId(row: MetaboDbRow) = db.run(MetaboDb.returning(MetaboDb.map(_.id)) += row)

  def deleteById(id: Int) = db.run(MetaboDb.filter(_.id === id).delete).map(_ => ())

  def selectByNameOp(userId: Int, name: String) = db.run(MetaboDb.
    filter(_.userId === userId).filter(_.dbName === name).result.headOption)

  def update(row: MetaboDbRow): Future[Unit] = db.run(MetaboDb.filter(_.id === row.id).update(row)).
    map(_ => ())

}
